﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace ConsoleApplicationTest
{
    public class Class1
    {
        private static Socket Serverlistener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private const int buffersize = 1024;
        private static byte[] ReceiveBuffer = new byte[buffersize];
        private int i = 0;
        public static void Main1(string[] args)
        {
            Console.Write("开始监听,等待连接中…… ");
            IPAddress ServerIpAddress = IPAddress.Parse("192.168.6.147");
            IPEndPoint localEndPoint = new IPEndPoint(ServerIpAddress, 11211);
            Serverlistener.Bind(localEndPoint);
            Serverlistener.Listen(100);
            Serverlistener.BeginAccept(new AsyncCallback(AcceptCallback), Serverlistener);
            Console.ReadLine();
        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            //   Get   the   socket   that   handles   the   client   request. 
            Socket Serverlistener = (Socket)ar.AsyncState;
            Socket ClientSocket = Serverlistener.EndAccept(ar);
            ClientSocket.BeginReceive(ReceiveBuffer, 0, buffersize, 0, new AsyncCallback(ReadCallback), ClientSocket);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty; 
            Socket ClientSocket = (Socket)ar.AsyncState;
            int bytesRead = ClientSocket.EndReceive(ar);
            if (bytesRead > 0)
            {
                content = Encoding.ASCII.GetString(ReceiveBuffer, 0, bytesRead);
                Console.Write(content);
                Send(ClientSocket, content);
            }
        }

        private static void Send(Socket ClientSocket, string content)
        {
            ClientSocket.Send(Encoding.ASCII.GetBytes(content));
        }
    }
}
